﻿using System;
using System.IO;
using System.Security.Cryptography;


namespace Enter.Admin.Utils
{
    public class FileIO
    {
        public static (FileInfo FileInfo, string PathName, string Extension) CreateFile(string fileName, bool isTemp = false)
        {
            // string filename = System.IO.Path.GetFileName(fullPath);//文件名 “Default.aspx”
            // string extension = System.IO.Path.GetExtension(fullPath);//扩展名 “.aspx”
            // string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(fullPath);// 没有扩展名的文件名 “Default”
            var extension = Path.GetExtension(fileName);
            var second = isTemp ? "Temp" : "File";
            var newFileName = Tools.NewGuid() + extension;
            var pathName = Path.Combine(second, DateTime.Now.ToString("yyyyMM"), newFileName);
            var fileInfo = GetFile(pathName);
            return (fileInfo, pathName, extension);
        }

        public static FileInfo GetFile(string pathName)
        {
            var root = Path.Combine(Directory.GetCurrentDirectory(), "Files");
            var fileInfo = new FileInfo(Path.Combine(root, pathName));
            if (!fileInfo.Directory.Exists)
            {
                fileInfo.Directory.Create();
            }
            return fileInfo;
        }

        public static string Md5(FileInfo filePath)
        {
            using (var fs = filePath.OpenRead())
            {
                HashAlgorithm algo = new MD5CryptoServiceProvider();//new SHA1CryptoServiceProvider(); new SHA256CryptoServiceProvider();  new SHA512CryptoServiceProvider();
                var hash = algo.ComputeHash(fs);
                //StringBuilder result = new StringBuilder();
                //for (int i = 0; i < hash.Length; i++)
                //{
                //    result.Append(hash[i].ToString("x2"));
                //}
                //var s = result.ToString();
                return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
            }
        }
    }
}
